package com.example.demo.util;

import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ImgUtil {

    public static List<String> setImgUrl(MultipartFile file, String url) {
        List<String> list = new ArrayList<>();
        if (file.isEmpty()) {
            list.add("false");
            list.add("上传失败，请选择文件");
            return list;
        }

        try {
            // 保存文件到本地目录
            Path imageDirectory = Paths.get(url);
            if (!Files.exists(imageDirectory)) {
                Files.createDirectories(imageDirectory);
            }
            Path targetLocation = imageDirectory.resolve(Objects.requireNonNull(file.getOriginalFilename()));
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 构造可以访问的图片URL
            list.add("true");
            list.add("/images/" + file.getOriginalFilename());
            return list;
        } catch (Exception ex) {
            list.add("false");
            list.add("上传失败：" + ex.getMessage());
            return list;

        }
    }
}
